package ve.usb.crm;

import com.itextpdf.text.BadElementException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;
import org.hibernate.Session;
import ve.usb.cohesion.runtime.HibernateUtil;
import ve.usb.crm.hibernate.Documento;
import ve.usb.crm.hibernate.Factura;
import ve.usb.crm.hibernate.FacturaCatalogo;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import java.io.FileOutputStream;
import java.util.Calendar;

public class AccionesDescargarFactura extends DownloadAction {

    protected StreamInfo getStreamInfo(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {

        Session s = HibernateUtil.getCurrentSession();
        Long idFactura = new Long(request.getParameter("idFactura"));

        Factura factura = (Factura) s.load(Factura.class, idFactura);

       
        List<FacturaCatalogo> productos = (List<FacturaCatalogo>) s.createQuery("from FacturaCatalogo where idFactura = "
                + ":idfactura").setLong("idfactura", idFactura).list();
        
        File facturaPdf = GUARDAR_PDF(factura, productos);

        String contentType = new MimetypesFileTypeMap().getContentType(facturaPdf);
        
        

        return new FileStreamInfo(contentType, facturaPdf);

    }

    public File GUARDAR_PDF(Factura factura, List<FacturaCatalogo> productos) throws FileNotFoundException, BadElementException, MalformedURLException, IOException {

        System.out.println("Creando Factura # 1 ...");


        String filePath =
                getServlet().getServletContext().getRealPath("/") + "facturasTmp";

        File folder = new File(filePath);
        if (!folder.exists()) {
            folder.mkdir();
        }


        Iterator<FacturaCatalogo> it = productos.iterator();




        Document document = new Document(PageSize.A4);



        try {



            PdfWriter.getInstance(document, new FileOutputStream("" + filePath + "/FACTURA-" + factura.getIdFactura() + ".pdf"));




            document.open();


            while (it.hasNext()) {


                Image img1 = Image.getInstance("/home/vanessa/Desktop/tesis/web/css/images/Factura_Vacia.jpg");//agrega imagen
                img1.scaleToFit(680, 680);//escala de la imagen
                img1.setAlignment(Image.MIDDLE | Image.UNDERLYING);//imagen centrada y de fondo.
                document.add(img1);


                PdfPCell cell;



                //[TABLA #1]

                PdfPTable table = new PdfPTable(1);

                Font FUENTE_NUM = new Font(Font.FontFamily.COURIER, 22, Font.BOLD, new BaseColor(255, 0, 0));

                //Font FUENTE_NUM = new Font( "COURIER",Font.BOLD,22);


                cell = new PdfPCell(new Paragraph(""));
                cell.setFixedHeight(33f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);

                cell = new PdfPCell(new Paragraph("" + factura.getIdFactura() + "", FUENTE_NUM));
                cell.setFixedHeight(42f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                Calendar cal = Calendar.getInstance();
                cell = new PdfPCell(new Paragraph("        " + cal.get(Calendar.DATE) + "            " + (cal.get(Calendar.MONTH)+1) + "      " + cal.get(Calendar.YEAR) + ""));
                cell.setFixedHeight(30f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                table.addCell(cell);




                float[] widths = {130f};//ancho tabla
                Rectangle r = new Rectangle(PageSize.A4.getRight(150), PageSize.A4.getTop(120));

                table.setWidthPercentage(widths, r);

                table.setHorizontalAlignment(Element.ALIGN_RIGHT);

                table.setSpacingBefore(50);

                document.add(table);//AGREGAR TABLA #1 AL DOCUMENTO

                //[TABLA #2]

                PdfPTable table2 = new PdfPTable(2);

                cell = new PdfPCell(new Paragraph(""));
                cell.setFixedHeight(30f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table2.addCell(cell);

                cell = new PdfPCell(new Paragraph(""));
                cell.setFixedHeight(30f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table2.addCell(cell);

                cell = new PdfPCell(new Paragraph(factura.getNombre()));
                cell.setFixedHeight(24f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table2.addCell(cell);

                cell = new PdfPCell(new Paragraph(factura.getRifCedula()));
                cell.setFixedHeight(24f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table2.addCell(cell);

                cell = new PdfPCell(new Paragraph(factura.getDireccion()));
                cell.setFixedHeight(26f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table2.addCell(cell);

                cell = new PdfPCell(new Paragraph(factura.getCodigoPostal()));
                cell.setFixedHeight(26f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table2.addCell(cell);

                cell = new PdfPCell(new Paragraph(factura.getCiudad()));
                cell.setFixedHeight(20f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table2.addCell(cell);

                cell = new PdfPCell(new Paragraph(factura.getTelefono()));
                cell.setFixedHeight(20f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table2.addCell(cell);



                float[] widths2 = {277f, 143f};//ancho tabla
                Rectangle r2 = new Rectangle(PageSize.A4.getRight(150), PageSize.A4.getTop(120));

                table2.setWidthPercentage(widths2, r2);

                table2.setHorizontalAlignment(Element.ALIGN_CENTER);
                table2.setSpacingBefore(50);


                document.add(table2);//AGREGAR TABLA #2 AL DOCUMENTO


                //[TABLA #3]



                PdfPTable table3 = new PdfPTable(6);



                float Alto3 = 22f;



                //[1]

                float monto = 0;
                for (int i = 0; i < 10; i++) {

                    if (it.hasNext()) {
                        FacturaCatalogo facturaCatalogo = it.next();

                        monto += (facturaCatalogo.getIdCatalogo().getCosto() * facturaCatalogo.getCantidad());

                        cell = new PdfPCell(new Paragraph("" + facturaCatalogo.getCantidad() + ""));
                        cell.setFixedHeight(Alto3);
                        cell.setBorder(PdfPCell.NO_BORDER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);

                        cell = new PdfPCell(new Paragraph("" + facturaCatalogo.getIdCatalogo().getNombre() + ""));
                        cell.setFixedHeight(Alto3);
                        cell.setBorder(PdfPCell.NO_BORDER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);

                        cell = new PdfPCell(new Paragraph(""));
                        cell.setFixedHeight(Alto3);
                        cell.setBorder(PdfPCell.NO_BORDER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);

                        cell = new PdfPCell(new Paragraph("" + facturaCatalogo.getIdCatalogo().getCodigo() + ""));
                        cell.setFixedHeight(Alto3);
                        cell.setBorder(PdfPCell.NO_BORDER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);

                        cell = new PdfPCell(new Paragraph("" + facturaCatalogo.getIdCatalogo().getCosto() + ""));
                        cell.setFixedHeight(Alto3);
                        cell.setBorder(PdfPCell.NO_BORDER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);

                        float importe = facturaCatalogo.getIdCatalogo().getCosto()*facturaCatalogo.getCantidad();

                        cell = new PdfPCell(new Paragraph("" + importe + ""));
                        cell.setFixedHeight(Alto3);
                        cell.setBorder(PdfPCell.NO_BORDER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);
                    } else {


                        cell = new PdfPCell(new Paragraph(""));
                        cell.setFixedHeight(Alto3);
                        cell.setBorder(PdfPCell.NO_BORDER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);

                        cell = new PdfPCell(new Paragraph(""));
                        cell.setFixedHeight(Alto3);
                        cell.setBorder(PdfPCell.NO_BORDER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);

                        cell = new PdfPCell(new Paragraph(""));
                        cell.setFixedHeight(Alto3);
                        cell.setBorder(PdfPCell.NO_BORDER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);

                        cell = new PdfPCell(new Paragraph(""));
                        cell.setFixedHeight(Alto3);
                        cell.setBorder(PdfPCell.NO_BORDER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);

                        cell = new PdfPCell(new Paragraph(""));
                        cell.setFixedHeight(Alto3);
                        cell.setBorder(PdfPCell.NO_BORDER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);

                        cell = new PdfPCell(new Paragraph());
                        cell.setFixedHeight(Alto3);
                        cell.setBorder(PdfPCell.NO_BORDER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);
                    }



                }




                float[] widths3 = {35f, 110f, 60f, 75f, 75f, 78f};//ancho tabla
                Rectangle r3 = new Rectangle(PageSize.A4.getRight(150), PageSize.A4.getTop(120));

                table3.setWidthPercentage(widths3, r3);

                table3.setHorizontalAlignment(Element.ALIGN_CENTER);
                table3.setSpacingBefore(28);

                document.add(table3);//AGREGAR TABLA #3 AL DOCUMENTO

                //[TABLA #4]

                PdfPTable table4 = new PdfPTable(1);

                Font FUENTE_TOT = new Font(Font.FontFamily.COURIER, 12, Font.BOLD, new BaseColor(255, 0, 0));

                //Font FUENTE_TOT = new Font( "COURIER",Font.BOLD,22);

                cell = new PdfPCell(new Paragraph(""+factura.getMonto()+"", FUENTE_TOT));
                cell.setFixedHeight(22f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table4.addCell(cell);

                float iva = (float) (monto * 0.14);

                cell = new PdfPCell(new Paragraph(""+factura.getIva()+"", FUENTE_TOT));
                cell.setFixedHeight(25f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table4.addCell(cell);

                float total = factura.getMonto()+factura.getIva();
                cell = new PdfPCell(new Paragraph(""+total+"", FUENTE_TOT));
                cell.setFixedHeight(20f);
                cell.setBorder(PdfPCell.NO_BORDER);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table4.addCell(cell);




                float[] widths4 = {100f};//ancho tabla
                Rectangle r4 = new Rectangle(PageSize.A4.getRight(150), PageSize.A4.getTop(120));

                table4.setWidthPercentage(widths4, r4);

                table4.setHorizontalAlignment(Element.ALIGN_RIGHT);
                table4.setSpacingBefore(50);

                document.add(table4);//AGREGAR TABLA #1 AL DOCUMENTO


            }
        } catch (DocumentException de) {
            System.err.println(de.getMessage());


        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());


        }


        document.close();


        File retorno = new File("" + filePath + "/FACTURA-" + factura.getIdFactura() + ".pdf");

        return retorno;



    }
}
